package com.lib.utils;

import androidx.annotation.NonNull;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

/**
 * @author FengLing
 * Created on 2017-05-22 19:02
 */
public class SignUtils {

    public static String getSign(@NonNull HashMap<String, String> map) {

        ArrayList<Map.Entry<String, String>> list = new ArrayList<>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
            @Override
            public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                return (o1.getKey().compareTo(o2.getKey()));
            }
        });
        StringBuilder sb = new StringBuilder();
        int size = list.size();
        for (int i = 0; i < size; i++) {
            sb.append("&").append(list.get(i));
        }
        return get32MD5(sb.toString().substring(1).toLowerCase());
    }

    /***
     * MD5加码 生成32位md5码
     */
    private static String get32MD5(String string) {

        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        string = string.concat("&app_secret=c1f94c61be734a209958c3be47652720");
        byte[] charArray = string.getBytes();
        byte[] byteArray = new byte[charArray.length];
        System.arraycopy(charArray, 0, byteArray, 0, charArray.length);
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuilder sb = new StringBuilder();
        for (byte md5Byte : md5Bytes) {
            int val = ((int) md5Byte) & 0xff;
            if (val < 16) {
                sb.append("0");
            }
            sb.append(Integer.toHexString(val));
        }
        return sb.toString();
    }
}